﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using WordXmlPart = Microsoft.Office.Core.CustomXMLPart;

namespace CodeCounsel.Office.DatabindingToolkit
{
    public class CustomXmlPart
       : INotifyPropertyChanged
    {
        WordXmlPart _wordXmlPart = null;
        List<CustomXmlNode> _rootNodes = null;
        bool _hasInitializedFromDocumentElement = false;

        public IEnumerable<CustomXmlNode> RootNodes
        {
            get
            {
                if (_hasInitializedFromDocumentElement == false)
                {
                    InitializeFromDocumentElement();
                }
                return _rootNodes;
            }
        }

        internal WordXmlPart WordXmlPart
        {
            get { return _wordXmlPart; }
        }

        public string ID
        {
            get { return _wordXmlPart.Id; }
        }

        public string NamespaceUri
        {
            get { return _wordXmlPart.NamespaceURI; }
        }

        public CustomXmlPart(WordXmlPart wordXmlPart)
        {
            _wordXmlPart = wordXmlPart;
            _rootNodes = new List<CustomXmlNode>();
            InitializeFromDocumentElement();
        }

        internal string LookupPrefix(string namespaceUri)
        {
            return _wordXmlPart.NamespaceManager.LookupPrefix(namespaceUri);
        }

        private void InitializeFromDocumentElement()
        {
            if (_wordXmlPart.DocumentElement != null)
            {
                _rootNodes.Add(new CustomXmlNode(this, _wordXmlPart.DocumentElement));
                _hasInitializedFromDocumentElement = true;
            }
        }

        protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

}
